<template>
  <div>
    <el-upload :action="api + '/file/upload'" :headers="headers" :class="{ hide: hideUpload }" :disabled="disabled"
      :file-list="imageUrl" :limit="limit" :on-change="dealImgChange" :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove" :on-success="handleAvatarSuccess" :on-progress="handleProgress" :on-error="handleError"
      list-type="picture-card">
      <i class="el-icon-plus"></i>
    </el-upload>

    <imageViewer :z-index="999999" :initial-index="imageIndex" :on-close="closeViewer" v-if="showViewer"
      :url-list="urlList" />
  </div>
</template>

<script>
import imageViewer from './image-viewer'
export default {
  name: "imgUpload",
  props: {
    disabled: {
      type: Boolean,
      // 对象或数组默认值必须从一个工厂函数获取
      default: false,
    },
    limit: {
      type: Number,
      // 对象或数组默认值必须从一个工厂函数获取
      default: function () {
        return 6
      }
    },
    imageUrl: Array,
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: [],
      imageIndex: 0,
      showViewer: false,
      urlList: [],
    };
  },
  watch: {
    dialogImageUrl(val) {

    }
  },
  components: { imageViewer },
  computed: {
    headers() {
      return {
        token: sessionStorage.getItem('token')
      }
    },
    api() {
      return this.$config.host
    },
    hideUpload() {
      return this.imageUrl.length >= this.limit
    },
  },
  methods: {
    closeViewer() {
      this.showViewer = false;
    },
    handlePictureCardPreview(file) {
      console.log(file)
      this.showViewer = true;
      this.urlList = [file.url]
    },
    getString() {
      let list = [];
      this.imageUrl.map(ele => {
        list.push(ele.url)
      })
      return list.join(",");
    },
    getList() {
      let list = [];
      this.imageUrl.map(ele => {
        list.push(ele.url)
      })
      return list;
    },
    handleAvatarSuccess(res, file) {
      // console.log(res);
      if (res.errcode == 0) {
        this.imageUrl.push({ url: res.data.urlPath })
        this.$emit('image')
      } else {
        this.err({ message: res.errmsg });
      }
    },
    // 上传时
    handleProgress() {
      this.$emit('progress');
    },
    // 上传失败
    handleError() {
      this.$emit('error');
    },
    handleRemove(file, fileList) {
      let delPath = file.url
      this.imageUrl.forEach((ele, index) => {
        if (ele.url == delPath) {
          this.imageUrl.splice(index, 1)
        }
      })

    },
    dealImgChange(file, fileList) {

    },
  },
  created() {

  },
  mounted() {

  },
  beforeDestroy() {

  },
  destroyed() {
  },
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
::v-deep .hide .el-upload--picture-card {
  display: none !important;
}

::v-deep .el-dialog__body {
  text-align: center;
}

::v-deep .el-upload-list__item {
  transition: none;
}
</style>
